import { useEffect, useState } from 'react'
import { useNavigate, Link } from 'react-router-dom';

import { NavBar, Toast } from 'antd-mobile';

import { getAreaMapInfo, getHouseList } from '../../api/request';

import './index.scss'
import styles from './index.module.scss'

export default function Map() {

  const navigate = useNavigate();
  // 小区的房屋信息
  const [houseList, setHouseList] = useState([]);
  // 是否展示房屋列表
  const [isShowHouseList, setIsHouseList] = useState(false);
  const getMap = () => {
    var map = new window.BMapGL.Map("container");
    const { label, value } = JSON.parse(localStorage.getItem('city'));
    //创建地址解析器实例
    var myGeo = new window.BMapGL.Geocoder();
    // 将地址解析结果显示在地图上，并调整地图视野
    myGeo.getPoint(label, async function (point) {
      if (point) {
        // 地图初始化
        initMap(map, point);
        Toast.show({
          icon: 'loading',
          content: '加载中…',
          duration: 0
        });
        // 获取当地房源信息
        const res = await getAreaMapInfo(value);
        // 创建覆盖物
        createOverlay(res.data.body, map, true, 13);
        Toast.clear();
      } else {
        alert('您选择的地址没有解析到结果！');
      }
    }, label);
    map.addEventListener('dragstart', () => {
      setIsHouseList(false);


    })
  }

  // 初始化地图
  const initMap = (map, point) => {
    map.centerAndZoom(point, 11);
    map.addOverlay(new window.BMapGL.Marker(point, { title: point }))
    var scaleCtrl = new window.BMapGL.ScaleControl();  // 添加比例尺控件
    map.addControl(scaleCtrl);
    var zoomCtrl = new window.BMapGL.ZoomControl();  // 添加缩放控件
    map.addControl(zoomCtrl);

  }

  // 创建覆盖物
  const createOverlay = (data, map, bool, grade) => {
    data.forEach(item => {
      // 设置文本覆盖物
      let opts = {
        position: new window.BMapGL.Point(item.coord.longitude, item.coord.latitude),
        offset: new window.BMapGL.Size(-30, -30),
      }
      const label = new window.BMapGL.Label("", opts);
      label.id = item.value;
      // 设置自定义dom的覆盖物
      label.setContent(getOverlayDom_circle(item, grade));
      // 覆盖物样式
      label.setStyle(getOverlay_style(bool));
      label.addEventListener("click", async function (e) {
        if (grade === 17) {
          // 弹出房屋消息
          // 获取房屋信息
          Toast.show({
            icon: 'loading',
            content: '加载中…',
            duration: 0
          });
          const { data: { body: { list } } } = await getHouseList(label.id);
          Toast.clear();
          setHouseList(list);
          setIsHouseList(true);
          const target = e.domEvent.changedTouches[0]
          map.panBy(window.innerWidth / 2 - target.clientX, (window.innerHeight - 330) / 2 - target.clientY);
        } else {
          map.centerAndZoom(new window.BMapGL.Point(item.coord.longitude, item.coord.latitude), grade);
          map.clearOverlays();
          Toast.show({
            icon: 'loading',
            content: '加载中…',
            duration: 0
          });
          let { data: { body } } = await getAreaMapInfo(label.id);
          createOverlay(body, map, grade === 15, grade + 2);
          Toast.clear();
        }

      });
      // 添加覆盖物到地图
      map.addOverlay(label);
    });
  };

  // 覆盖物的 圆形 dom
  const getOverlayDom_circle = (item, grade) => {
    let dom = grade === 17 ? (`<div class="rectangle">
    <p class="name">${item.label}</p>
    <p>${item.count}套</p>
    </div>`) : (`<div class="bubble">
    <p class="name">${item.label}</p>
    <p>${item.count}套</p>
    </div>`)

    return dom;
  };

  // 覆盖物 的样式
  /*
  参数的含义
  true 图形覆盖物就是长方形
  false 是圆形
  */
  const getOverlay_style = (bool) => ({
    color: '#FFF',
    fontSize: '13px',
    borderRadius: bool ? '0' : '50%',
    border: '2px solid #1E90FF',
    backgroundColor: 'rgba(12,181,106,0.9)'
  })

  const back = () => {
    navigate(-1);
  }

  useEffect(() => {
    getMap();
  }, [])
  return (
    <div className='content'>

      <NavBar back='返回' onBack={back} className='tab'>
        地图找房
      </NavBar>

      <div id="container"></div>

      {/* 房源列表 */}
      {/* 添加 styles.show 展示房屋列表 */}
      <div
        className={[
          styles.houseList,
          isShowHouseList ? styles.show : ''
        ].join(' ')}
      >
        <div className={styles.titleWrap}>
          <h1 className={styles.listTitle}>房屋列表</h1>
          <Link className={styles.titleMore} to="/home/list">
            更多房源
          </Link>
        </div>

        <div className={styles.houseItems}>
          {/* 房屋结构 */}
          {houseList.map(item => (
            <div className={styles.house} key={item.houseCode}>
              <div className={styles.imgWrap}>
                <img
                  className={styles.img}
                  src={`http://localhost:8080${item.houseImg}`}
                  alt=""
                />
              </div>
              <div className={styles.content}>
                <h3 className={styles.title}>{item.title}</h3>
                <div className={styles.desc}>{item.desc}</div>
                <div>
                  {item.tags.map((tag, index) => (
                    <span
                      className={[styles.tag, styles.tag1].join(' ')}
                      key={tag}
                    >
                      {tag}
                    </span>
                  ))}
                </div>
                <div className={styles.price}>
                  <span className={styles.priceNum}>{item.price}</span> 元/月
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>


  )
}
